import React, { useState, useEffect } from 'react';
import CustomSelect from '../../CustomSelect';
import './FormField.css';

const FormField = ({
  label,
  required = false,
  type = 'text',
  placeholder = '请输入内容',
  options = [],
  value = '',
  arrayValue = null, // 用于数组类型字段的完整数组值
  onChange = () => {},
  onAdd = null,
  onRemove = null,
  className = ''
}) => {
  const [fieldValue, setFieldValue] = useState(value);

  // 同步外部value的变化
  useEffect(() => {
    setFieldValue(value);
  }, [value]);

  const handleChange = (e) => {
    const newValue = e.target.value;
    setFieldValue(newValue);
    onChange(newValue);
  };

  const handleSelectChange = (value) => {
    setFieldValue(value);
    onChange(value);
  };

  const handleAdd = () => {
    if (onAdd) {
      onAdd();
    }
  };

  const handleRemove = () => {
    if (onRemove) {
      onRemove();
    }
  };

  const renderInput = () => {
    switch (type) {
      case 'select':
        // 转换 options 格式为 CustomSelect 需要的格式
        const selectOptions = [
          { value: '', label: placeholder },
          ...options.map((option) => ({
            value: option.value !== undefined ? option.value : option,
            label: option.label !== undefined ? option.label : option
          }))
        ];
        
        return (
          <CustomSelect
            options={selectOptions}
            value={fieldValue || ''}
            onChange={handleSelectChange}
            placeholder={placeholder}
            showSelected={true}
            className="form-field__custom-select"
          />
        );
      case 'textarea':
        return (
          <textarea
            className="form-field__input form-field__textarea"
            placeholder={placeholder}
            value={fieldValue}
            onChange={handleChange}
            rows={3}
          />
        );
      default:
        return (
          <input
            type={type}
            className="form-field__input"
            placeholder={placeholder}
            value={fieldValue}
            onChange={handleChange}
          />
        );
    }
  };

  // 检查字段是否有值（处理字符串和数组类型）
  const hasValue = () => {
    // 如果是数组类型字段，使用arrayValue来判断
    if (type === 'array' && arrayValue) {
      return arrayValue.length > 0 && arrayValue.some(item => item && item.trim() !== '');
    }
    // 普通字段使用fieldValue判断
    return fieldValue !== '' && fieldValue != null;
  };

  return (
    <div className={`form-field ${className}`}>
      <label className="form-field__label">
        {label}
        {required && !hasValue() && <span className="form-field__required">*</span>}
      </label>
      
      <div className="form-field__input-container">
        {renderInput()}
        
        {onAdd && (
          <button
            type="button"
            className="form-field__add-btn"
            onClick={handleAdd}
          >
            <span className="form-field__add-icon">+</span>
          </button>
        )}
        
        {onRemove && (
          <button
            type="button"
            className="form-field__remove-btn"
            onClick={handleRemove}
          >
            <span className="form-field__remove-icon">×</span>
          </button>
        )}
      </div>
    </div>
  );
};

export default FormField;
